﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	RouterFormatter.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Text;

namespace Smart.Common.Router
{
	/// <summary>
	/// Router formatter
	/// </summary>
	public class RouterFormatter
	{
		/// <summary>
		/// Router context
		/// </summary>
		public RouterContext Ctx { get; set; }

		/// <summary>
		/// Router formatter
		/// </summary>
		public RouterFormatter(RouterContext ctx)
		{
			Ctx = ctx;
		}

		/// <summary>
		/// Format template uri using values
		/// </summary>
		/// <returns>Formatted uri</returns>
		public virtual string FormatUri()
		{
			try
			{
				var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
				var sb = new StringBuilder();
				var parts = Ctx.Template.Uri.Split(false, Const.Template.TagSymbol);

				if (parts.Length <= 2)
					return Ctx.Template.Uri;

				var source = Ctx.Service.Source;

				sb.Append(parts[0]);

				int I;

				for (I = 1; I < parts.Length - 1; I++)
				{
					var templateValuePart = parts[I];

					if (tags.ContainsKey(templateValuePart))
					{
						sb.Append(tags[templateValuePart]);
						sb.Append(parts[++I]);
						continue;
					}

					if (templateValuePart.Length > 32)
					{
						sb.Append(Const.Template.TagSymbol);
						sb.Append(templateValuePart);
						continue;
					}

					string partValue;

					if (source.GetUriPartValue(templateValuePart, out partValue))
					{
						tags[templateValuePart] = partValue;

						sb.Append(partValue);
						sb.Append(parts[++I]);
					}
					else
					{
						sb.Append(Const.Template.TagSymbol);
						sb.Append(templateValuePart);
					}
				}

				if (I < parts.Length)
				{
					sb.Append(Const.Template.TagSymbol);
					sb.Append(parts[I]);
				}

				return sb.ToString();
			}
			catch (Exception x)
			{
				H.LX("RouterFormatter.FormatUri", x);
			}

			return Ctx.Template.Uri;
		}
	}
}